/*
 * @Description: 登录
 * @Author: kanglin
 * @Date: 2018-06-08 18:15:40
 * @Copyright: Created by Panxsoft.
 */

import axios from 'axios';
// import Vue from 'vue';
import API_LIST from 'src/API_LIST';

/**
 *
 * @param {*} key
 * @param {*} value
 */
function setStringCache(key, value) {
	sessionStorage.setItem(key, value);
}

function getStringCache(key) {
	return sessionStorage.getItem(key) || null;
}

const state = {
	phone: getStringCache('user_phone'),
};

/* eslint-disable no-shadow, no-param-reassign */

const mutations = {
	setUserPhone(state, phone) {
		state.phone = phone;
		setStringCache('user_phone', phone);
	},
};

const getters = {
	getUserPhone(state) {
		return state.phone;
	},
};

const actions = {
	/**
	 * 登录接口请求
	 * @param {*} context
	 * @param {*} params
	 */
	loginH5User(context, params) {
		return axios.post(API_LIST.H5_LOGIN, params)
			.then(({ data }) => {
				if (parseInt(data.code, 10) !== 0) {
					throw new Error(data.error);
				} else {
					const { wechat_user } = data;
					context.commit('userInfo/setUserInfo', wechat_user, { root: true });
					context.commit('userInfo/initDataComplete', true, { root: true });
					context.commit('setUserPhone', wechat_user.phone);
					return wechat_user;
				}
			});
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters,
};
